﻿using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Bluetooth
{
    public partial class Form1 : Form
    {
        private delegate void wtSetList(string str);//委托
        private delegate void wtSetTxt(string str);//委托
        private string address;
        BluetoothRadio BuleRadio = null;//蓝牙适配器  
        string sendFileName = null;//发送文件名  
        private int n = 0;
        ObexListener listener = null;//监听器  
        string recDir = null;//接受文件存放目录  
        Thread listenThread, sendThread;//发送/接收线程  
        private Boolean isConnected = false;
        BluetoothClient Blueclient;
        Dictionary<string, BluetoothAddress> deviceAddresses = new Dictionary<string, BluetoothAddress>();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            BuleRadio = BluetoothRadio.PrimaryRadio;
            if (BuleRadio == null)
            {
                MessageBox.Show("未能在此设备找到蓝牙模块！");
                this.Close();
                return;
            }
            BuleRadio.Mode = RadioMode.Connectable;
            Blueclient = new BluetoothClient();
            EventHandler<BluetoothWin32AuthenticationEventArgs> handler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(this.handleRequests);
            BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(handler);
        }
        private void btnFind_Click(object sender, EventArgs e)
        {
            this.lblMessage.Text = "正在搜索周围的设备，请稍候。。。";
            this.lblMessage.Visible = true;

            lsbDevices.Items.Clear();
            n = 0;
            //启动一个监听线程
            Thread listenThread = new Thread(FindBluetooth);
            listenThread.IsBackground = true;
            listenThread.Start();

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //启动一个监听线程
            Thread listenThread = new Thread(ReceiveData);
            listenThread.IsBackground = true;
            listenThread.Start();
            setText("正在配对，请稍候");
        }
        public void handleRequests(Object thing, BluetoothWin32AuthenticationEventArgs args)
        {
            args.Confirm = true;
        }
        private void setList(string str)
        {
            lsbDevices.Items.Add(str);
            n++;
            lblMessage.Text="搜索完毕，共搜索到[" +n+ "]个设备！";
        }
        private void setText(string str)
        {
            lblMessage.Text += str + "\r\n";
        }
        public void FindBluetooth()
        {
            BluetoothDeviceInfo[] Devices = Blueclient.DiscoverDevices();
            deviceAddresses.Clear();
            foreach (BluetoothDeviceInfo device in Devices)
            {
                this.Invoke(new wtSetList(setList), device.DeviceName);
                deviceAddresses[device.DeviceName] = device.DeviceAddress;
            }
        }
        //监听方法
        public void ReceiveData()
        {
            try
            {
                BluetoothAddress DeviceAddress = deviceAddresses[address];
                //Blueclient.SetPin(DeviceAddress, "1234");
                Blueclient.Connect(DeviceAddress, BluetoothService.Handsfree);
                this.Invoke(new wtSetTxt(setText), "配对成功！");
                isConnected = true;
                startListener();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                isConnected = false;
            }
            while (isConnected)
            {
                string receive = string.Empty;
                if (Blueclient == null)
                {
                    break;
                }
                try
                {
                    Stream peerStream = Blueclient.GetStream();
                    byte[] buffer = new byte[6];
                    peerStream.Read(buffer, 0, 6);
                    receive = Encoding.UTF8.GetString(buffer).ToString();
                    this.Invoke(new wtSetTxt(setText), receive);
                }
                catch (System.Exception)
                {
                }
                Thread.Sleep(100);
            }
        }

        private void lsbDevices_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lsbDevices.SelectedItem == null) return;
            address = lsbDevices.SelectedItem.ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendFileName = dialog.FileName;//设置文件名  
                txt_msg.Text = Path.GetFileName(sendFileName);
                sendThread = new Thread(sendFile);//开启发送文件线程  
                sendThread.Start();
            }
        }

        private void txt_msg_MouseClick(object sender, MouseEventArgs e)
        {

        }
        private void sendFile()//发送文件方法  
        {
            BluetoothAddress DeviceAddress = deviceAddresses[address];
            ObexWebRequest request = new ObexWebRequest(DeviceAddress, Path.GetFileName(sendFileName));//创建网络请求  
            WebResponse response = null;
            try
            {
               // button3.Enabled = false;
                request.ReadFile(sendFileName);//发送文件  
                this.Invoke(new wtSetTxt(setText), "开始发送!");
                response = request.GetResponse();//获取回应  
                this.Invoke(new wtSetTxt(setText), "发送完成!");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("发送失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.Invoke(new wtSetTxt(setText), "发送失败!");
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    button3.Enabled = true;
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择蓝牙接收文件的存放路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                recDir = dialog.SelectedPath;
                tb_receivePath.Text = recDir;
            }
        }

        private void receiveFile()//收文件方法  
        {
            ObexListenerContext context = null;
            ObexListenerRequest request = null;
            while (listener.IsListening)
            {
                context = listener.GetContext();//获取监听上下文  
                if (context == null)
                {
                    break;
                }
                request = context.Request;//获取请求  
                string uriString = Uri.UnescapeDataString(request.RawUrl);//将uri转换成字符串  
                string recFileName = recDir + uriString;
                request.WriteFile(recFileName);//接收文件
                this.Invoke(new wtSetTxt(setText), "收到文件" + uriString.TrimStart(new char[] { '/' }));
            }
        }
        private void startListener()//开始/停止监听  
        {
            if (listener == null || !listener.IsListening)
            {
                BuleRadio.Mode = RadioMode.Discoverable;//设置本地蓝牙可被检测  
                listener = new ObexListener(ObexTransport.Bluetooth);//创建监听  
                listener.Start();
                if (listener.IsListening)
                {
                    this.Invoke(new wtSetTxt(setText), "开始监听接收文件");
                    listenThread = new Thread(receiveFile);//开启监听线程  
                    listenThread.Start();
                }
            }
            else
            {
                listener.Stop();
                this.Invoke(new wtSetTxt(setText), "监听停止");
            }
        }
    }
}
